<template>
  <div class="product-card">

        <!--这个地方增加一个日历占位符-->
        <div class="calendar-placeholder w-full mb-4 bg-white rounded-lg p-4">
        <div class="flex items-center justify-between mb-2">
          <span class="text-lg font-medium">日历</span>
          <div class="flex items-center gap-2">
            <el-button type="primary" link>
              <Icon icon="ep:arrow-left" />
            </el-button>
            <span class="text-sm">2025年6月</span>
            <el-button type="primary" link>
              <Icon icon="ep:arrow-right" />
            </el-button>
          </div>
        </div>
        <div class="grid grid-cols-7 gap-1 text-center">
          <div class="text-sm text-gray-400">日</div>
          <div class="text-sm text-gray-400">一</div>
          <div class="text-sm text-gray-400">二</div>
          <div class="text-sm text-gray-400">三</div>
          <div class="text-sm text-gray-400">四</div>
          <div class="text-sm text-gray-400">五</div>
          <div class="text-sm text-gray-400">六</div>
        </div>
        <div class="grid grid-cols-7 gap-1 mt-2">
          <div
v-for="i in 31" :key="i" 
            class="aspect-square flex items-center justify-center text-sm cursor-pointer hover:bg-gray-100 rounded"
            :class="{'text-gray-400': i > 28}"
          >
            {{ i }}
          </div>
        </div>
      </div>

    <div class="card-header">
      <span class="title">{{ property.title }}</span>
      <el-image v-if="property.titleIcon" :src="property.titleIcon" class="title-icon" />
      <div class="flex-1"></div>
      <span v-if="property.moreLink" class="more-link" @click="goMore">
        查看更多 <el-image v-if="property.moreIcon" :src="property.moreIcon" class="more-icon" />
        </span>
    </div>
    <div :class="`box-content min-h-30px w-full flex flex-row flex-wrap`" ref="containerRef">
      <!-- 活动主题横向滚动 -->
      <!-- <div class="topic-tabs">
        <div
          v-for="topic in topicList"
          :key="topic.id"
          :class="['topic-tab', { active: topic.id === topicId }]"
          :style="topic.id === topicId
            ? {
                color: '#fff',
                fontWeight: 'bold',
              }
            : {
                color: '#374e60',
                borderBottom: '2px solid transparent',
                background: '#f7f7f7'
              }"
          @click="onTopicChange(topic.id)"
        >
          {{ topic.name }}
        </div>
      </div> -->
      
  
      
      <div
        class="relative box-content flex flex-row flex-wrap overflow-hidden bg-white"
        :style="{
          ...calculateSpace(index),
          ...calculateWidth(),
          borderTopLeftRadius: `${property.borderRadiusTop}px`,
          borderTopRightRadius: `${property.borderRadiusTop}px`,
          borderBottomLeftRadius: `${property.borderRadiusBottom}px`,
          borderBottomRightRadius: `${property.borderRadiusBottom}px`
        }"
        v-for="(product, index) in productList"
        :key="index"
      >
        <!-- 角标 -->
        <div v-if="property.badge.show" class="absolute left-0 top-0 z-1 items-center justify-center">
          <el-image fit="cover" :src="property.badge.imgUrl" class="h-26px w-38px" />
        </div>
        <!-- 商品封面图 -->
        <div
          :class="[
            'h-140px',
            {
              'w-full': property.layoutType !== 'oneColSmallImg',
              'w-140px': property.layoutType === 'oneColSmallImg'
            }
          ]"
        >
          <el-image fit="cover" class="h-full w-full" :src="product.picUrl" />
        </div>
        <div
          :class="[
            ' flex flex-col gap-8px p-8px box-border',
            {
              'w-full': property.layoutType !== 'oneColSmallImg',
              'w-[calc(100%-140px-16px)]': property.layoutType === 'oneColSmallImg'
            }
          ]"
        >
          <!-- 商品名称 -->
          <div
            v-if="property.fields.name.show"
            :class="[
              'text-14px ',
              {
                truncate: property.layoutType !== 'oneColSmallImg',
                'overflow-ellipsis line-clamp-2': property.layoutType === 'oneColSmallImg'
              }
            ]"
            :style="{ color: property.fields.name.color }"
          >
            {{ product.name }}
          </div>
          <!-- 商品简介 -->
          <div
            v-if="property.fields.introduction.show"
            class="truncate text-12px"
            :style="{ color: property.fields.introduction.color }"
          >
            {{ product.introduction }}
          </div>
          <!-- 商品价格 -->
          <div
            v-if="property.fields.price.show"
            class="text-14px"
            :style="{ color: property.fields.price.color }"
          >
            ¥{{ product.price }}
          </div>
          <!-- 市场价 -->
          <div
            v-if="property.fields.marketPrice.show"
            class="text-12px"
            :style="{ color: property.fields.marketPrice.color }"
          >
            市场价：¥{{ product.marketPrice }}
          </div>
          <!-- 商品销量 -->
          <div
            v-if="property.fields.salesCount.show"
            class="text-12px"
            :style="{ color: property.fields.salesCount.color }"
          >
            销量：{{ product.salesCount }}
          </div>
          <!-- 商品库存 -->
          <div
            v-if="property.fields.stock.show"
            class="text-12px"
            :style="{ color: property.fields.stock.color }"
          >
            库存：{{ product.stock }}
          </div>
        </div>
        <!-- 立即购买按钮 -->
        <div v-if="property.btnType.type === 'buy' && property.btnShow" class="absolute bottom-8px right-8px">
          <!-- 文字按钮 -->
          <span
            v-if="property.btnBuy.type === 'text'"
            class="rounded-full p-x-12px p-y-4px text-12px text-white"
            :style="{
              background: `linear-gradient(to right, ${property.btnBuy.bgBeginColor}, ${property.btnBuy.bgEndColor}`
            }"
          >
            {{ property.btnBuy.text }}
          </span>
          <!-- 图片按钮 -->
          <el-image
            v-else
            class="h-28px w-28px rounded-full"
            fit="cover"
            :src="property.btnBuy.imgUrl"
          />
        </div>

        <!-- 加入购物车按钮 -->
        <div v-if="property.btnType.type === 'cart' && property.btnShow" class="absolute bottom-8px right-8px">
          <!-- 文字按钮 -->
          <span
            v-if="property.btnCart.type === 'text'"
            class="rounded-full p-x-12px p-y-4px text-12px text-white"
            :style="{
              background: `linear-gradient(to right, ${property.btnCart.bgBeginColor}, ${property.btnBuy.bgEndColor}`
            }"
          >
            {{ property.btnCart.text }}
          </span>
          <!-- 图片按钮 -->
          <el-image
            v-else
            class="h-28px w-28px rounded-full"
            fit="cover"
            :src="property.btnCart.imgUrl"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ProductCardProperty } from './config'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { ActivityTopicApi,ActivityTopicVO } from '@/api/mall/promotion/activityTopic'
import { ActivityTopicProductVO, ActivityTopicProductApi} from '@/api/mall/promotion/ActivityTopicProduct'

/** 商品卡片 */
defineOptions({ name: 'CalenderActivityProductCard' })
// 定义属性
const props = defineProps<{ property: ProductCardProperty }>()
// 商品列表
const productList = ref<ProductSpuApi.Spu[]>([])
// 活动主题列表
const topicList = ref<ActivityTopicVO[]>([])
const topicId = ref(0)

const fetchTopicList = async () => {
  if (props.property.topicIds) {
    const topics = await Promise.all(props.property.topicIds.map(id => ActivityTopicApi.getActivityTopicById(id)))
    topicList.value = topics

    if (topicList.value.length > 0) {
      onTopicChange(topicList.value[0].id)
    }
  }
}

const onTopicChange = async (id: number) => {
  topicId.value = id
  const products = await ActivityTopicProductApi.getActivityTopicProductPage({
    topicId: id,
    pageNo: 1,
    pageSize: 10
  })

  if (products.list && products.list.length > 0) {
    const spuIds = products.list.map(item => item.spuId)
    const spuList = await ProductSpuApi.getSpuDetailList(spuIds);
   
    productList.value = spuList
  } else {
    productList.value = []
  }
}

// 监听活动主题ID变化
watch(
  () => props.property.topicIds,
  async (newIds) => {
    debugger
    if (newIds.length > 0) {
      const topics = await Promise.all(newIds.map(id => ActivityTopicApi.getActivityTopicById(id)))
      topicList.value = topics
      if (topicList.value.length > 0) {
        onTopicChange(topicList.value[0].id)
      }
    } else {
      topicList.value = []
    }
  },
  {
    immediate: true,
    deep: true
  }
)

/**
 * 计算商品的间距
 * @param index 商品索引
 */
const calculateSpace = (index: number) => {
  // 商品的列数
  const columns = props.property.layoutType === 'twoCol' ? 2 : 1
  // 第一列没有左边距
  const marginLeft = index % columns === 0 ? '0' : props.property.space + 'px'
  // 第一行没有上边距
  const marginTop = index < columns ? '0' : props.property.space + 'px'

  return { marginLeft, marginTop }
}

// 容器
const containerRef = ref()
// 计算商品的宽度
const calculateWidth = () => {
  let width = '100%'
  // 双列时每列的宽度为：（总宽度 - 间距）/ 2
  if (props.property.layoutType === 'twoCol') {
    width = `${(containerRef.value.offsetWidth - props.property.space) / 2}px`
  }
  return { width }
}

const goMore = () => {
  if (props.property.moreLink) {
    window.open(props.property.moreLink, '_blank')
  }
}

onMounted(async () => {
  await fetchTopicList()
})
</script>

<style scoped lang="scss">
.product-card {
  padding: 12px 12px 0;
  background: #fff;
  border-radius: 12px;

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .title {
      margin-right: 4px;
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 600;
      color: #222;
    }

    .title-icon {
      width: 18px;
      height: 18px;
      margin-right: 4px;
    }

    .more-link {
      display: flex;
      align-items: center;
      cursor: pointer;

      .more-icon {
        width: 18px;
        height: 18px;
      }
    }
  }
}

.topic-tabs {
  display: flex;
  margin-bottom: 12px;
  overflow-x: auto;
  white-space: nowrap;
}

.topic-tab {
  width: 143px;
  padding: 8px 16px;
  margin-right: 8px;
  cursor: pointer;
  background: linear-gradient(180.00deg, #d1e8ff 0%, #fff 100%);
  border-bottom: 2px solid transparent;
  border-radius: 37px;
  transition: color 0.2s, border-bottom 0.2s;
  user-select: none;
}
</style>
